// src/pages/admin/torrent/PendingTorrents.jsx
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Table, Button, Tag, Space, Card, Spin, message, Popconfirm, Modal, Descriptions } from 'antd';
import { FileTextOutlined, CheckOutlined, CloseOutlined, EyeOutlined } from '@ant-design/icons';
import axios from 'axios';
import { getAuthToken } from '@/router';
import moment from 'moment';
import 'moment/locale/zh-cn';

// Mock data for when API fails (更新为匹配新API结构)
const mockPendingTorrents = {
  data: {
    records: [
      {
        id: 1,
        infoHash: "abc123def456",
        name: '示例电影资源',
        size: 104857600,
        category: 'movie',
        description: '这是一部经典电影',
        tags: "动作,冒险",
        uploaderName: '模拟用户1',
        downloadCount: 0,
        seederCount: 0,
        leecherCount: 0,
        status: 'checking',
        isFree: 0,
        createdAt: "2024-06-01T12:00:00",
        updatedAt: "2024-06-01T12:00:00"
      },
      {
        id: 2,
        infoHash: "xyz789uvw456",
        name: '示例音乐专辑',
        size: 52428800,
        category: 'music',
        description: '流行音乐合集',
        tags: "流行,摇滚",
        uploaderName: '模拟用户2',
        downloadCount: 0,
        seederCount: 0,
        leecherCount: 0,
        status: 'checking',
        isFree: 0,
        createdAt: "2024-06-01T13:00:00",
        updatedAt: "2024-06-01T13:00:00"
      }
    ],
    current: 1,
    total: 2,
    pages: 1
  }
};

const PendingTorrents = () => {
  const [loading, setLoading] = useState(true);
  const [torrents, setTorrents] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedTorrent, setSelectedTorrent] = useState(null);
  const [rejectModalVisible, setRejectModalVisible] = useState(false);
  const [rejectReason, setRejectReason] = useState('');
  const [tempRejectRecord, setTempRejectRecord] = useState(null);
  const navigate = useNavigate();

  const fetchData = async (page = 1, pageSize = 10, category = 'all') => {
    try {
      setLoading(true);
      const response = await axios.get('http://192.168.55.192:8080/api/admin/torrent/pending', {
        params: { page, size: pageSize, category },
        headers: { Authorization: getAuthToken() }
      });
      
      if (response.data.code === 200) {
        setTorrents(response.data.data.records);
        setPagination({
          current: response.data.data.current,
          pageSize: response.data.data.size || pageSize,
          total: response.data.data.total
        });
      } else {
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      console.error('获取待审核种子失败，使用模拟数据:', error);
      setTorrents(mockPendingTorrents.data.records);
      setPagination({
        current: mockPendingTorrents.data.current,
        pageSize: mockPendingTorrents.data.size || 10,
        total: mockPendingTorrents.data.total
      });
      message.warn('后端连接失败，使用模拟数据');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleTableChange = (pagination) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleReview = async (torrentId, status, reason = '') => {
    try {
      await axios.post('http://192.168.55.192:8080/api/admin/torrent/review', 
        [{ torrentId, status, rejectReason: reason }],
        { headers: { Authorization: getAuthToken() } }
      );
      message.success('操作成功');
      fetchData(pagination.current, pagination.pageSize);
      setRejectModalVisible(false);
      setRejectReason('');
      
      // 如果当前有详情弹窗打开，关闭它
      if (detailVisible) {
        setDetailVisible(false);
      }
    } catch (error) {
      console.error('审核操作失败:', error);
      message.error('操作失败');
    }
  };

  const handleViewDetail = (torrent) => {
    setSelectedTorrent(torrent);
    setDetailVisible(true);
  };

  const showRejectModal = (record) => {
    setTempRejectRecord(record);
    setRejectModalVisible(true);
  };

  // 在详情弹窗中处理拒绝操作
  const handleRejectInDetail = () => {
    setTempRejectRecord(selectedTorrent);
    setRejectModalVisible(true);
  };

  // 在详情弹窗中处理通过操作
  const handleApproveInDetail = () => {
    handleReview(selectedTorrent.id, 'approved');
    setDetailVisible(false);
  };

  const getStatusTag = (status) => {
    const statusMap = {
      'checking': { text: '待审核', color: 'orange' },
      'approved': { text: '已通过', color: 'green' },
      'rejected': { text: '已拒绝', color: 'red' }
    };
    
    const statusInfo = statusMap[status] || { text: '未知状态', color: 'gray' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  const columns = [
    {
      title: '种子名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Button type="link" onClick={() => handleViewDetail(record)}>
          <FileTextOutlined /> {text}
        </Button>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: category => <Tag color="blue">{category}</Tag>
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
      render: size => `${(size / 1024 / 1024).toFixed(2)} MB`
    },
    {
      title: '上传者',
      dataIndex: 'uploaderName',
      key: 'uploaderName'
    },
    {
      title: '上传时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: createdAt => moment(createdAt).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: getStatusTag
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="primary" 
            icon={<CheckOutlined />} 
            onClick={() => handleReview(record.id, 'approved')}
          >
            通过
          </Button>
          <Button 
            danger 
            icon={<CloseOutlined />} 
            onClick={() => showRejectModal(record)}
          >
            拒绝
          </Button>
          <Button 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            查看详情
          </Button>
        </Space>
      )
    }
  ];

  return (
    <Card 
      title="待审核种子" 
      bordered={false}
      extra={<Button type="primary" onClick={() => fetchData()}>刷新</Button>}
    >
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={torrents}
          rowKey="id"
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Spin>
      
      {/* 种子详情模态框 */}
      <Modal
        title={`种子详情 - ${selectedTorrent?.name || ''}`}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {selectedTorrent && (
          <div style={{ padding: 20 }}>
            <Descriptions bordered>
              <Descriptions.Item label="ID" span={3}>{selectedTorrent.id}</Descriptions.Item>
              <Descriptions.Item label="名称" span={3}>{selectedTorrent.name}</Descriptions.Item>
              <Descriptions.Item label="分类">{selectedTorrent.category}</Descriptions.Item>
              <Descriptions.Item label="大小">{(selectedTorrent.size / 1024 / 1024).toFixed(2)} MB</Descriptions.Item>
              <Descriptions.Item label="上传者">{selectedTorrent.uploaderName}</Descriptions.Item>
              <Descriptions.Item label="状态">{getStatusTag(selectedTorrent.status)}</Descriptions.Item>
              <Descriptions.Item label="下载次数">{selectedTorrent.downloadCount}</Descriptions.Item>
              <Descriptions.Item label="种子数">{selectedTorrent.seederCount}</Descriptions.Item>
              <Descriptions.Item label="下载人数">{selectedTorrent.leecherCount}</Descriptions.Item>
              <Descriptions.Item label="上传时间" span={3}>
                {moment(selectedTorrent.createdAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="标签" span={3}>
                {selectedTorrent.tags}
              </Descriptions.Item>
              <Descriptions.Item label="描述" span={3}>
                {selectedTorrent.description}
              </Descriptions.Item>
            </Descriptions>
            
            {/* 在详情弹窗中添加操作按钮 */}
            <div style={{ marginTop: 20, textAlign: 'right' }}>
              <Space>
                <Button 
                  type="primary" 
                  icon={<CheckOutlined />}
                  onClick={handleApproveInDetail}
                >
                  通过审核
                </Button>
                <Button 
                  danger 
                  icon={<CloseOutlined />}
                  onClick={handleRejectInDetail}
                >
                  拒绝
                </Button>
                <Button onClick={() => setDetailVisible(false)}>关闭</Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>

      {/* 拒绝原因输入模态框 */}
      <Modal
        title="拒绝原因"
        open={rejectModalVisible}
        onOk={() => handleReview(tempRejectRecord?.id, 'rejected', rejectReason)}
        onCancel={() => {
          setRejectModalVisible(false);
          setRejectReason('');
        }}
        okText="确认拒绝"
        cancelText="取消"
      >
        {tempRejectRecord && (
          <>
            <p>请输入拒绝种子 "{tempRejectRecord.name}" 的原因：</p>
            <textarea 
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              placeholder="请填写拒绝原因..."
              style={{ width: '100%', minHeight: 100, padding: 8 }}
            />
          </>
        )}
      </Modal>
    </Card>
  );
};

export default PendingTorrents;